package com.wyj.utils

import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.hjq.gson.factory.GsonFactory

object JsonUtil {
    @JvmStatic
    @JvmOverloads
    fun getString(obj: JsonObject?, fieldName: String, default: String? = ""): String? {
        val e = obj?.get(fieldName)
        if (e == null || e.isJsonNull) {
            return default
        }
        val result = e.asString
        return if (Utils.isNullOrEmpty(result)) default else result
    }

    @JvmStatic
    @JvmOverloads
    fun getInt(obj: JsonObject?, fieldName: String, default: Int = 0): Int {
        return getString(obj, fieldName)?.trim()?.toDoubleOrNull()?.toInt() ?: default
    }

    @JvmStatic
    @JvmOverloads
    fun getBoolean(obj: JsonObject?, fieldName: String, default: Boolean = false): Boolean {
        return try {
            GsonFactory.getSingletonGson().fromJson(obj?.get(fieldName)?.asString,Boolean::class.java)?:default
        } catch (e: Exception) {
            default
        }
    }

    @JvmStatic
    @JvmOverloads
    fun getDouble(obj: JsonObject?, fieldName: String, default: Double = 0.0): Double {
        return getString(obj, fieldName)?.trim()?.toDoubleOrNull() ?: default
    }


    @JvmStatic
    fun getJsonArray(obj: JsonObject?, fieldName: String): JsonArray? {
        val e = obj?.get(fieldName)
        if (e == null || e.isJsonNull) {
            return null
        }
        return try {
            e.asJsonArray
        } catch (e: Exception) {
            null
        }
    }

    @JvmStatic
    fun getJsonObjectList(obj: JsonObject?, fieldName: String): ArrayList<JsonObject> {
        val list = arrayListOf<JsonObject>()
        getJsonArray(obj, fieldName)?.map { it.asJsonObject }?.let(list::addAll)
        return list
    }
}